/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.fenyin.samples.study.netty.http;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.DynamicChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;


import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Handler implementation for the echo server.
 */
public class HttpServerHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = Logger.getLogger(HttpServerHandler.class.getName());

    private final AtomicLong transferredBytes = new AtomicLong();
    
    private TransferService transferService;
    
    public HttpServerHandler(String filePath){
    	transferService = new TransferService(filePath);
    }

    public long getTransferredBytes() {
        return transferredBytes.get();
    }
    
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    	//获取HttpRequest请求
    	HttpRequest request = (HttpRequest) e.getMessage();
    	String uri = request.getUri();
    	System.out.println("uri:"+uri);
    	
    	HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    	//应答内容
    	String content = transferService.transfer(uri);
    	ChannelBuffer buffer=new DynamicChannelBuffer(content.length());
    	buffer.writeBytes(content.getBytes());
//    	try {
//    		
//		} catch (UnsupportedEncodingException e1) {
//			logger.log(Level.INFO, "发生异常");
//		}
    	response.setContent(buffer);
    	response.setHeader("Content-Type", "text/xml; charset=UTF-8");
    	Channel ch = e.getChannel();
    	// Write the initial line and the header.
    	ch.write(response);
    	ch.disconnect();
    	ch.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        // Close the connection when an exception is raised.
        logger.log(
                Level.WARNING,
                "Unexpected exception from downstream.",
                e.getCause());
        e.getChannel().close();
    }
}
